<template>
  <div class="performance-monitor">
    <el-card class="monitor-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><Monitor /></el-icon>
            性能监控
          </span>
          <el-button 
            type="primary" 
            size="small" 
            @click="refreshStats"
            :loading="loading"
          >
            刷新
          </el-button>
        </div>
      </template>

      <!-- 系统状态概览 -->
      <div class="status-overview">
        <div class="status-item">
          <div class="status-label">系统状态</div>
          <el-tag 
            :type="systemStatus.type" 
            size="large"
            class="status-tag"
          >
            {{ systemStatus.text }}
          </el-tag>
        </div>
        
        <div class="status-item">
          <div class="status-label">缓存健康</div>
          <el-tag 
            :type="cacheHealth.type" 
            size="large"
            class="status-tag"
          >
            {{ cacheHealth.text }}
          </el-tag>
        </div>
        
        <div class="status-item">
          <div class="status-label">内存使用</div>
          <div class="memory-usage">
            <el-progress 
              :percentage="memoryUsage" 
              :color="getMemoryColor(memoryUsage)"
              :show-text="false"
            />
            <span class="memory-text">{{ memoryUsage }}%</span>
          </div>
        </div>
      </div>

      <!-- 缓存统计 -->
      <div class="cache-stats">
        <h4>缓存统计</h4>
        <el-row :gutter="16">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ cacheStats.memory?.size || 0 }}</div>
              <div class="stat-label">内存缓存</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ cacheStats.localStorage?.size || 0 }}</div>
              <div class="stat-label">本地缓存</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-value">{{ cacheStats.sessionStorage?.size || 0 }}</div>
              <div class="stat-label">会话缓存</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 性能指标 -->
      <div class="performance-metrics">
        <h4>性能指标</h4>
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="metric-item">
              <div class="metric-value">{{ performanceMetrics.responseTime }}ms</div>
              <div class="metric-label">平均响应时间</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="metric-item">
              <div class="metric-value">{{ performanceMetrics.cacheHitRate }}%</div>
              <div class="metric-label">缓存命中率</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="metric-item">
              <div class="metric-value">{{ performanceMetrics.errorRate }}%</div>
              <div class="metric-label">错误率</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="metric-item">
              <div class="metric-value">{{ performanceMetrics.throughput }}</div>
              <div class="metric-label">吞吐量/分钟</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 优化建议 -->
      <div class="recommendations" v-if="recommendations.length > 0">
        <h4>优化建议</h4>
        <el-alert
          v-for="(rec, index) in recommendations"
          :key="index"
          :title="rec"
          type="info"
          :closable="false"
          class="recommendation-item"
        />
      </div>

      <!-- 操作按钮 -->
      <div class="actions">
        <el-button 
          type="warning" 
          @click="clearLowPriorityCache"
          :loading="clearing"
        >
          清理低优先级缓存
        </el-button>
        <el-button 
          type="danger" 
          @click="clearAllCache"
          :loading="clearing"
        >
          清空所有缓存
        </el-button>
        <el-button 
          type="success" 
          @click="optimizePerformance"
          :loading="optimizing"
        >
          性能优化
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Monitor } from '@element-plus/icons-vue'
import { CacheUtils } from '@/utils/apiCache'
import { SecurityUtils } from '@/utils/security'

// 响应式数据
const loading = ref(false)
const clearing = ref(false)
const optimizing = ref(false)

const cacheStats = reactive({
  memory: { size: 0, maxSize: 100 },
  localStorage: { size: 0 },
  sessionStorage: { size: 0 }
})

const performanceMetrics = reactive({
  responseTime: 0,
  cacheHitRate: 0,
  errorRate: 0,
  throughput: 0
})

const recommendations = ref([])
const memoryUsage = ref(0)

// 计算属性
const systemStatus = computed(() => {
  if (performanceMetrics.errorRate > 5) {
    return { type: 'danger', text: '异常' }
  } else if (memoryUsage.value > 80) {
    return { type: 'warning', text: '警告' }
  } else {
    return { type: 'success', text: '正常' }
  }
})

const cacheHealth = computed(() => {
  const health = CacheUtils.getHealthStatus()
  const typeMap = {
    'healthy': 'success',
    'warning': 'warning',
    'critical': 'danger'
  }
  const textMap = {
    'healthy': '健康',
    'warning': '警告',
    'critical': '危险'
  }
  return {
    type: typeMap[health.status] || 'info',
    text: textMap[health.status] || '未知'
  }
})

// 定时器
let statsTimer = null

// 方法
const refreshStats = async () => {
  loading.value = true
  try {
    // 获取缓存统计
    const stats = CacheUtils.getStats()
    Object.assign(cacheStats, stats)
    
    // 获取缓存健康状态
    const health = CacheUtils.getHealthStatus()
    memoryUsage.value = health.memoryUsage
    recommendations.value = health.recommendations
    
    // 模拟性能指标（实际项目中应该从真实的监控系统获取）
    performanceMetrics.responseTime = Math.round(Math.random() * 200 + 50)
    performanceMetrics.cacheHitRate = Math.round(Math.random() * 30 + 70)
    performanceMetrics.errorRate = Math.round(Math.random() * 3)
    performanceMetrics.throughput = Math.round(Math.random() * 100 + 50)
    
  } catch (error) {
    console.error('获取性能统计失败:', error)
    ElMessage.error('获取性能统计失败')
  } finally {
    loading.value = false
  }
}

const getMemoryColor = (percentage) => {
  if (percentage > 90) return '#f56c6c'
  if (percentage > 70) return '#e6a23c'
  return '#67c23a'
}

const clearLowPriorityCache = async () => {
  clearing.value = true
  try {
    CacheUtils.clearByPriority(['low'])
    ElMessage.success('已清理低优先级缓存')
    await refreshStats()
  } catch (error) {
    console.error('清理缓存失败:', error)
    ElMessage.error('清理缓存失败')
  } finally {
    clearing.value = false
  }
}

const clearAllCache = async () => {
  clearing.value = true
  try {
    CacheUtils.clearAll()
    ElMessage.success('已清空所有缓存')
    await refreshStats()
  } catch (error) {
    console.error('清空缓存失败:', error)
    ElMessage.error('清空缓存失败')
  } finally {
    clearing.value = false
  }
}

const optimizePerformance = SecurityUtils.debounce(async () => {
  optimizing.value = true
  try {
    // 执行性能优化
    CacheUtils.smartCleanup()
    
    // 预热关键缓存
    await CacheUtils.warmupSmart()
    
    ElMessage.success('性能优化完成')
    await refreshStats()
  } catch (error) {
    console.error('性能优化失败:', error)
    ElMessage.error('性能优化失败')
  } finally {
    optimizing.value = false
  }
}, 1000)

// 生命周期
onMounted(() => {
  refreshStats()
  
  // 每30秒自动刷新统计
  statsTimer = setInterval(refreshStats, 30000)
})

onUnmounted(() => {
  if (statsTimer) {
    clearInterval(statsTimer)
  }
})
</script>

<style scoped>
.performance-monitor {
  padding: 20px;
}

.monitor-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.status-overview {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.status-item {
  flex: 1;
  text-align: center;
}

.status-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.status-tag {
  font-weight: 600;
}

.memory-usage {
  display: flex;
  align-items: center;
  gap: 8px;
}

.memory-text {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  min-width: 40px;
}

.cache-stats,
.performance-metrics {
  margin-bottom: 24px;
}

.cache-stats h4,
.performance-metrics h4,
.recommendations h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
}

.stat-item,
.metric-item {
  text-align: center;
  padding: 16px;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
}

.stat-value,
.metric-value {
  font-size: 24px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label,
.metric-label {
  font-size: 12px;
  color: #909399;
}

.recommendations {
  margin-bottom: 24px;
}

.recommendation-item {
  margin-bottom: 8px;
}

.actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .status-overview {
    flex-direction: column;
    gap: 16px;
  }
  
  .actions {
    flex-direction: column;
  }
}
</style>